#!/usr/bin/env python
# encoding: utf-8

import binascii
class Help:
    def lora_cmd_deal(self, recv):
        '''串口处理命令，监测校验和是否正确'''
        if recv.startswith('AA'):
            data = recv[4:-2]
            theory_len =  int(recv[2:4], 16)
            real_len = int(len(data)/2)
            if theory_len == real_len:
                data_list = [int(data[i:i+2], 16) for i in range(0,len(data)) if i%2==0]
                s = hex(sum(data_list) % 256).replace('0x','').zfill(2)[-2:]
                _sum = recv[-2:]
                if s == _sum:
                    addr    = data[0:8]
                    _type   = data[8:10]
                    cmd     = data[10:12]
                    content = data[12:]
                    res = {
                        'addr': addr,
                        'type': _type,
                        'cmd': cmd,
                        'data': content
                    }
                    return res
        return False

    def lora_get_cmd(self, lora_addr="", target="", local="",_type="",cmd="",content=""):
        # if not lora_addr:
        #     return "error lora_addr"
        # if not target:
        #     return "error target"
        # if not cmd:
        #     return "error cmd"
        # print("lora_addr:", lora_addr)
        # print("target:", target)
        # print("local:", local)
        # print("_type:", _type)
        # print("cmd:", cmd)
        # print("content:", content)
        header = 'AA'
        data = target+local+_type+cmd+content
        length = hex(int(len(data)/2)).replace('0x','').zfill(2)[-2:]
        if len(data) > 0 and len(data) % 2 == 0:
            data_list = [int(data[i:i+2], 16) for i in range(0,len(data)) if i%2==0]
            _sum = hex(sum(data_list) % 256).replace('0x','').zfill(2)[-2:]
            cmd = lora_addr+header+length+data+_sum
            cmd = binascii.unhexlify(cmd)
            return cmd
